package repository

import (
	"context"
	"database/sql"

	"gitee.com/hp-huiw/family-expense-api/internal/db"
	dbmodel "gitee.com/hp-huiw/family-expense-api/internal/db/model"
	jet "github.com/go-jet/jet/v2/mysql"
)

type Bank struct {
	ID        string `db:"id"`
	Name      string `db:"name"`
	ShortName string `db:"short_name"`
}

type BankRepository interface {
	Exists(ctx context.Context) (bool, error)
	QueryAllWithBasicInfo(ctx context.Context) ([]Bank, error)
	BatchInsert(ctx context.Context, models []dbmodel.Bank) error
}

func NewBankRepository(db *sql.DB) BankRepository {
	return &bankRepository{db: db}
}

func (r *bankRepository) Exists(ctx context.Context) (bool, error) {
	return db.Exists(ctx, r.db, tbBank, nil)
}

func (r *bankRepository) QueryAllWithBasicInfo(ctx context.Context) ([]Bank, error) {
	var query []struct {
		ID        string `db:"id"`
		Name      string `db:"name"`
		ShortName string `db:"short_name"`
	}

	stmt := jet.
		SELECT(
			tbBank.ID.AS("id"),
			tbBank.Name.AS("name"),
			tbBank.ShortName.AS("short_name"),
		).
		FROM(
			tbBank,
		)

	if err := stmt.QueryContext(ctx, r.db, &query); err != nil {
		return nil, err
	}

	result := make([]Bank, 0, len(query))

	for _, item := range query {
		result = append(result, item)
	}

	return result, nil
}

// BatchInsert inserts multiple banks.
func (r *bankRepository) BatchInsert(ctx context.Context, models []dbmodel.Bank) error {
	stmt := tbBank.
		INSERT().
		MODELS(models)

	_, err := stmt.ExecContext(ctx, r.db)

	return err
}

type bankRepository struct {
	db *sql.DB
}
